<template>
  <view>
    <kk-container
      class="kkContainer"
      ref="kkContainerRef"
      pageBackground="#F1F2F3"
      footerBackground="#F1F2F3"
      title="答疑详情"
      :isShowHeader="true"
      :showPageLoading="showPageLoading"
      :refresherEnabled="false"
      :showLoading="showLoading"
      :isSelfHandleBackAction="true"
      :touchEnable="true"
      :isShowCustomFooter="true"
      :scrollAnimation="scrollAnimation"
      :scrollEnabled="true"
      :footerHeight="footerHeight"
      @handlerScroll="handlerScroll"
      @slideDirection="slideDirection"
      @navigateBack="navigateBack"
    >
      <view class="kkMainContent" @tap="clickBgAction">
        <DetailCard
          v-show="asnwerUserInfo"
          :data="asnwerUserInfo"
          :status="answerStatus"
          :indexInfo="getUnResonseIndexInfo()"
          ref="detailCardRef"
          @focus="topFocus"
          @blur="topBlur"
          @confirmCalculateNum="confirmCalculateNum"
          @collectionQuestion="collectionQuestion"
        />
        <view
          v-if="isLoadingPageData"
          style="padding-top: 24rpx; padding-bottom: 0rpx"
        >
          <up-loading-icon mode="circle"></up-loading-icon>
        </view>

        <view class="conversationBg">
          <view v-for="(value, index) in list" :key="index">
            <Conversation
              :data="value"
              :tapBgNumber="tapBgNumber"
              :selectDatas="selectConversationList"
              :isSelectMode="isSelectMode"
              :orgIds="orgIds"
              @sendFail="sendFail"
              @reSendMsg="reSendMsg"
              @chatTipsClick="chatTipsClick"
              @conversationSlect="conversationSelect"
              @converstationTouchStart="converstationTouchStart"
              @converstationTouchEnd="converstationTouchEnd"
            />
          </view>
        </view>
      </view>

      <template v-slot:customFooter>
        <ChatBottom
          ref="chatBottomRef"
          v-if="bottomViewType === 'normal'"
          :topInputFoucs="topInputFoucs"
          @bottomHeightChange="bottomHeightChange"
          @scrollToBottom="scrollToBottom"
          @sendMsg="sendTextMsg"
          @sendImageAndVideo="sendImageAndVideo"
          @uploadAudio="uploadAudio"
          @bottomAiReplayTap="bottomAiReplayTap"
          @bottomPushExamTap="bottomPushExamTap"
        />
        <AiReplyBottom
          v-if="bottomViewType === 'ai'"
          @aiReplySelectConversation="aiReplySelectConversation"
        />
      </template>
    </kk-container>
    <AiReplayDialog
      v-if="showAiDialog"
      :show="showAiDialog"
      :aiReplayRequestParam="aiReplayRequestParam"
      @close="showAiDialog = false"
      @copyAiContent="copyAiContent"
    />
    <SimilarExamDialog
      ref="similarExamDialogRef"
      :show="showExamDialog"
      @close="showExamDialog = false"
      @confirmPushExam="confirmPushExam"
    />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, onUnmounted, computed } from "vue";
import { kkSliderDirection } from "@/components/common/enmu";
import "@/style/katex-mini.scss";
import {
  KKConversationFrom,
  KKConversationType,
  KKConversationStatus,
  KKConversationSource,
} from "./components/conversitonEnum";
import {
  getChatFrom,
  getChatTime,
  getChatSource,
  getChatContent,
  getChatType,
  getChatVideoPoster,
  getChatAudioDuration,
  getAnswerContent,
  getChatAiExamList,
} from "@/utils/chat";
import kkToast from "@/utils/kkToast";
import { generateUUID } from "@/utils/util";
import DetailCard from "./components/detailCard.vue";
import Conversation from "./components/conversation.vue";
import ChatBottom from "./chat/bottom.vue";
import AiReplyBottom from "./chat/aiReplyBottom.vue";
import AiReplayDialog from "./aiReplay/index.vue";
import SimilarExamDialog from "./components/exam/similarExamDialog.vue";
import { ossUploadFile, OSSFilePath } from "@/utils/useOss";
import * as KKAswerApi from "@/api/answer";
import * as OSSApi from "@/api/oss";
import * as KKApi from "@/api/index";

const tapBgNumber = ref(0); // 点击背景的次数
const currentId = ref();
const productId = ref("");
const kkContainerRef = ref();
const showLoading = ref(false);
const showPageLoading = ref(true);
const normalFooterHeight = 100;
const footerHeight = ref(normalFooterHeight);
const aiFooterHeight = 136;
const scrollAnimation = ref(true);
const maxScrollTop = ref(0);
const timer = ref(null);
const showAiDialog = ref(false);
const showExamDialog = ref(false);
const chatBottomRef = ref();

const isSelectMode = ref(false);
const bottomViewType = ref("normal"); //normal 正常 1：ai

const asnwerUserInfo = ref(); // 答疑用户信息
const answerStatus = ref(0); // status 状态，1：未回复 2：追问未回复 3：已回复 4：已完成
const page = ref(1);
const pageSize = 10;
const total = ref(1);
const isLoadAllData = ref(false);
const conversationCommonInfo = ref({});
const list = ref([]);
const aiReplayRequestParam = ref([]); //AI 回复参数列表
const isFromList = ref(true);
const unResponseInfo = ref({
  cnt: 0,
  ids: [],
});
const currentUnResponseIndex = ref(0);
const isScrollingBottom = ref(false);
const needClearHistoryList = ref(false);
const orgIds = ref([]); // 组织ids

onLoad((options) => {
  answerStatus.value = options?.status ? Number(options?.status) : 0;
  if (options?.id) {
    currentId.value = options?.id;
    isFromList.value = true;
    getAnswerUserInfo();
    getList(true);
    getUnResponseStatisticsProt();
  } else {
    isFromList.value = false;
    getUnResponseStatisticsProt();
  }
});

// 重置答疑详情数据 详情页请求新数据
const resetAnswerDetailData = () => {
  footerHeight.value = normalFooterHeight;
  isSelectMode.value = false;
  bottomViewType.value = "normal";
  page.value = 1;
  isLoadAllData.value = false;
  aiReplayRequestParam.value = {};
};

// 获取下一个未回复详情
// type next 下一个 pre上一个
const loadNextUnResonseDetail = (type: string) => {
  if (isSelectMode.value) {
    return;
  }
  if (answerStatus.value === 1 || answerStatus.value === 2) {
    if (type === "pre") {
      if (currentUnResponseIndex.value > 0) {
        currentUnResponseIndex.value -= 1;
      } else {
        // kkToast.showToast("暂无上一个");
      }
    } else if (type === "next") {
      if (currentUnResponseIndex.value < unResponseInfo.value.ids.length - 1) {
        currentUnResponseIndex.value += 1;
      } else {
        // kkToast.showToast("暂无下一个");
      }
    }
    if (currentUnResponseIndex.value < unResponseInfo.value.ids.length) {
      if (
        unResponseInfo.value.ids[currentUnResponseIndex.value] !==
        currentId.value
      ) {
        currentId.value =
          unResponseInfo.value.ids[currentUnResponseIndex.value];
        resetAnswerDetailData();
        isLoadingPageData.value = false;
        isScrollingBottom.value = true;
        showLoading.value = true;
        needClearHistoryList.value = true;
        getAnswerUserInfo();
        getList(true);
        getUnResponseStatisticsProt();
        showLoading.value = false;
      }
    }
  }
};

// 获取未回复定位信息
const getUnResonseIndexInfo = () => {
  let indexInfo = "";
  if (unResponseInfo.value && unResponseInfo.value.cnt > 0) {
    unResponseInfo.value.ids &&
      unResponseInfo.value.ids.forEach((item, index) => {
        if (item === currentId.value) {
          indexInfo = `${index + 1}/${unResponseInfo.value.cnt}`;
          currentUnResponseIndex.value = index;
        }
      });
  }
  return indexInfo;
};

// 获取未回复统计
const getUnResponseStatisticsProt = async () => {
  if (answerStatus.value === 1 || answerStatus.value === 2) {
    //status 1：未回复 2：追问未回复 3：已回复 4：已完成
    const param = {
      status: answerStatus.value,
    };
    const data = (await KKAswerApi.getUnResponseStatisticsProt(param).catch(
      () => {}
    )) as any;
    showPageLoading.value = false;
    if (data && data.data) {
      unResponseInfo.value = data.data;
      if (!isFromList.value) {
        if (
          !currentId.value &&
          unResponseInfo.value.ids &&
          unResponseInfo.value.ids.length === 0
        ) {
          if (answerStatus.value === 1) {
            kkToast.showToast("暂无未回复答疑");
          } else if (answerStatus.value === 2) {
            kkToast.showToast("暂无追问未回复答疑");
          }
          timer.value = setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          if (!currentId.value && unResponseInfo.value.ids.length > 0) {
            currentId.value = unResponseInfo.value.ids[0];
            getAnswerUserInfo();
            getList(true);
          }
        }
      }
    }
  }
};

const detailCardRef = ref();
// 获取答疑用户详情
const getAnswerUserInfo = async () => {
  const data = (await KKAswerApi.answerGetUserInfoProt(currentId.value).catch(
    () => {}
  )) as any;
  showPageLoading.value = false;
  if (data && data.data) {
    asnwerUserInfo.value = data.data;
    productId.value = asnwerUserInfo.value.productId || "";
    detailCardRef.value.initCalculateNum(
      Number(asnwerUserInfo.value.calculateNum)
    );
    if (answerStatus.value === 0) {
      // 需要从detail中获取状态
      // 答疑状态 状态，1：待分配，2：分配未回复，3：流转未回复，4：分配已回复，5：流转已回复，6：追问未回复，7：追问已回复，8：已完成
      const requestStatus = Number(asnwerUserInfo.value.requestStatus || "");
      if (requestStatus === 2 || requestStatus === 3) {
        answerStatus.value = 1;
      } else if (requestStatus === 6) {
        answerStatus.value = 2;
      } else if (
        requestStatus === 4 ||
        requestStatus === 5 ||
        requestStatus === 7
      ) {
        answerStatus.value = 3;
      } else if (requestStatus === 8) {
        answerStatus.value = 4;
      }
      if (answerStatus.value === 1 || answerStatus.value === 2) {
        getUnResponseStatisticsProt();
      }
    }
  }
};

const getList = async (scrollBottom: boolean) => {
  const param = {
    page: page.value,
    pageSize: pageSize,
    requestId: currentId.value,
  };
  const data = (await KKAswerApi.getHistoryListProt(param).catch(() => {
    isLoadingPageData.value = false;
  })) as any;
  showPageLoading.value = false;
  isLoadingPageData.value = false;
  if (param.requestId !== currentId.value) {
    return;
  }
  if (data && data.data) {
    conversationCommonInfo.value = data.data;
    total.value = data.data.total;
    orgIds.value = data.data.orgIds || [];
    if (needClearHistoryList.value) {
      list.value = [];
    }
    handleConversationData(
      data.data.historyNodeList || [],
      data.data.phoneHistoryNodeList || []
    );
    needClearHistoryList.value = false;
  }
  if (scrollBottom) {
    timer.value = setTimeout(() => {
      scrollAnimation.value = false;
      isScrollingBottom.value = true;
      scrollToBottom();
      timer.value = setTimeout(() => {
        scrollAnimation.value = true;
        isScrollingBottom.value = false;
      }, 1500);
    }, 100);
  } else {
    isScrollingBottom.value = true;
    timer.value = setTimeout(() => {
      isScrollingBottom.value = false;
    }, 1500);
  }
};

// 处理会话历史数据
const handleConversationData = (
  coversationList: [],
  phoneHistoryNodeList: []
) => {
  let newDataList = [];
  for (var i = coversationList.length - 1; i >= 0; i--) {
    const item = coversationList[i] as any;
    let isPhonePhoto = false;
    if (item.contentFlag === 2 && item.answerWay === 3) {
      // 拍搜AI回复
      isPhonePhoto = true;
    }
    let chatModel = {
      ...item,
      avatar: conversationCommonInfo.value.avatar,
      from: getChatFrom(item),
      source: getChatSource(item),
      time: getChatTime(item),
      chatType: getChatType(item),
      text: getChatContent(item),
      videoPoster: getChatVideoPoster(item),
      duration: getChatAudioDuration(item),
      status: KKConversationStatus.success,
      isSelect: false,
      isPhonePhoto,
      aiExamList: isPhonePhoto ? getChatAiExamList(item) : [],
    };
    if (
      chatModel.chatType === KKConversationType.text ||
      chatModel.chatType === KKConversationType.richText
    ) {
      if (chatModel.text) {
        newDataList.push(chatModel);
      }
    } else {
      newDataList.push(chatModel);
    }
  }
  if (page.value === 1) {
    list.value = newDataList;
  } else {
    list.value = [...newDataList, ...list.value];
  }
  if (
    (total.value > 0 && list.value.length >= total.value) ||
    coversationList.length === 0 ||
    coversationList.length < 10
  ) {
    list.value = [...getPhotoPhoneList(phoneHistoryNodeList), ...list.value];
    isLoadAllData.value = true;
  } else {
    isLoadAllData.value = false;
  }
};

// 获取拍照搜题结果
const getPhotoPhoneList = (phoneHistoryNodeList: []) => {
  let list = [];
  for (var i = 0; i < phoneHistoryNodeList.length; i++) {
    const item = phoneHistoryNodeList[i] as any;
    let isPhonePhoto = false;
    if (
      item.contentFlag === 2 &&
      (item.answerWay === 2 || item.answerWay === 3)
    ) {
      // 拍搜AI回复
      isPhonePhoto = true;
    }
    let aiExamList = [];
    if (isPhonePhoto && getChatType(item) === KKConversationType.exam) {
      aiExamList = getChatAiExamList(item);
    }
    let chatModel = {
      ...item,
      avatar: conversationCommonInfo.value.avatar,
      from: getChatFrom(item),
      source: getChatSource(item),
      time: getChatTime(item),
      chatType: getChatType(item),
      text: getChatContent(item),
      videoPoster: getChatVideoPoster(item),
      duration: getChatAudioDuration(item),
      status: KKConversationStatus.success,
      isSelect: false,
      isPhonePhoto,
      aiExamList: aiExamList || [],
    };
    if (
      chatModel.chatType === KKConversationType.text ||
      chatModel.chatType === KKConversationType.richText
    ) {
      if (chatModel.text) {
        list.push(chatModel);
      }
    } else {
      list.push(chatModel);
    }
  }
  return list || [];
};

// 已经选择的会话列表
const selectConversationList = computed(() => {
  return list.value.filter((item) => item.isSelect);
});

const topInputFoucs = ref(false);

const topFocus = () => {
  topInputFoucs.value = true;
};
const topBlur = () => {
  topInputFoucs.value = false;
};

// 点击整个页面背景
const clickBgAction = () => {
  tapBgNumber.value += 1;
};

// 确认核算次数
const confirmCalculateNum = (value: Number) => {
  asnwerUserInfo.value.calculateNum = value;
};

//收录试题
const collectionQuestion = async () => {
  if (showLoading.value) return;
  let status = 0;
  let msg = "已标记为收录试题，请自行录入题库-试题库";
  // 1：不收录，2：收录
  if (asnwerUserInfo.value.recordStatus === 1) {
    status = 2;
  } else if (asnwerUserInfo.value.recordStatus === 2) {
    status = 1;
    msg = "取消收录成功";
  }
  showLoading.value = true;
  const data = (await KKAswerApi.employQuestionProt({
    id: asnwerUserInfo.value.requestId,
    status,
  }).catch(() => {
    showLoading.value = false;
  })) as any;
  showLoading.value = false;
  if (data && Number(data.code) === 10000) {
    asnwerUserInfo.value.recordStatus = status;
    kkToast.showToast(msg);
  }
};

// 左侧返回
const navigateBack = () => {
  if (isSelectMode.value) {
    isSelectMode.value = false;
    clearConversationSelect();
    bottomViewType.value = "normal";
    footerHeight.value = normalFooterHeight;
  } else {
    uni.navigateBack();
  }
};

const handlerScroll = (scrollTop: number) => {
  if (scrollTop > maxScrollTop.value) {
    maxScrollTop.value = scrollTop;
  }
  if (scrollTop <= 100) {
    conversationReqPrePageData();
  }
};

const isLoadingPageData = ref(false);

const conversationReqPrePageData = () => {
  if (
    isLoadingPageData.value ||
    isLoadAllData.value ||
    isScrollingBottom.value
  ) {
    return;
  }
  isLoadingPageData.value = true;
  page.value += 1;
  getList(false);
};

const bottomHeightChange = (height: number) => {
  footerHeight.value = height;
};

const kkContainerHeight = ref(0);
const lastScrollTop = ref(0);

const scrollToBottom = () => {
  if (kkContainerHeight.value) {
    uni
      .createSelectorQuery()
      .select(".kkMainContent")
      .boundingClientRect((rect) => {
        // console.log(
        //   rect,
        //   kkContainerHeight.value,
        //   footerHeight.value,
        //   uni.upx2px(footerHeight.value)
        // );
        if (rect.height) {
          let scrollTop =
            rect.height -
            kkContainerHeight.value +
            uni.upx2px(footerHeight.value) +
            126;
          if (scrollTop === lastScrollTop.value) {
            scrollTop += 0.00001;
          }
          timer.value = setTimeout(() => {
            kkContainerRef.value.setScrollTop(scrollTop);
            lastScrollTop.value = scrollTop;
          }, 100);
        }
      })
      .exec();
  } else {
    uni
      .createSelectorQuery()
      .select(".kkContainer")
      .boundingClientRect((rect) => {
        kkContainerHeight.value = rect.height;
        scrollToBottom();
      })
      .exec();
  }
};
// 滑动方向
const slideDirection = (direction: kkSliderDirection) => {
  if (subViewTouchStart.value) {
    return;
  }
  switch (direction) {
    case kkSliderDirection.left:
      {
        console.log("向左滑动");
        loadNextUnResonseDetail("pre");
      }
      break;
    case kkSliderDirection.right:
      {
        console.log("向右滑动");
        loadNextUnResonseDetail("next");
      }
      break;
  }
};

onUnmounted(() => {
  if (timer.value) {
    clearTimeout(timer.value);
  }
});

// ################################## OSS上传相关逻辑 #################################
const ossConfig = ref<any>();
const baseFileReqUrl = ref<string>("");
const initOssConfig = async () => {
  const { data } = (await OSSApi.fetchOSSConfig().catch(
    () => {}
  )) as KKApi.KKResponseData;
  if (data) {
    ossConfig.value = data || {};
    baseFileReqUrl.value = `https://${ossConfig.value.bucketName}.${ossConfig.value.endPoint}`;
    return true;
  } else {
    ossConfig.value = {};
    baseFileReqUrl.value = "";
    return false;
  }
};
// 上传文件
const uploadFile = async (file: any, ossFilePath: OSSFilePath) => {
  const initOss = await initOssConfig().catch(() => {});
  if (initOss) {
    const result = (await ossUploadFile(
      file,
      baseFileReqUrl.value,
      ossFilePath
    )) as any;
    return result;
  } else {
    kkToast.showToast("上传失败，请稍后重试");
    return "";
  }
};

// ################################## 发送相关逻辑 #################################

// 发送失败按钮点击
const sendFail = (data: any) => {
  const index = findConversationIndex(data.id);
  if (index < list.value.length) {
    list.value[index].status = KKConversationStatus.retry;
  }
};

// 重新发送消息点击
const reSendMsg = (data: any) => {
  const index = findConversationIndex(data.id);
  if (index < list.value.length) {
    list.value[index].status = KKConversationStatus.loading;
  }
  aswerMessageSend(data);
};

// 聊天提示点击
const chatTipsClick = (data: any) => {
  const type = data.type;
  if (type === "select") {
    // 多选
    isSelectMode.value = true;
    bottomViewType.value = "ai";
    footerHeight.value = aiFooterHeight;
    if (data.data && data.data.chatType === KKConversationType.text) {
      //选择文本
      conversationSelect(data.data);
    }
  } else if (type === "ai") {
    // AI回复
    if (data.data) {
      aiReplySelectConversation([data.data]);
    }
  }
};

// 会话选择
const conversationSelect = (data: any) => {
  const index = findConversationIndex(data.id);
  const selectConversation = list.value.filter((item: any) => item.isSelect);
  if (!list.value[index].isSelect && selectConversation.length >= 5) {
    return;
  }

  if (data.chatType === KKConversationType.img) {
    list.value[index].isSelect = !list.value[index].isSelect;
    list.value.forEach((item: any) => {
      if (item.chatType === KKConversationType.img && item.id !== data.id) {
        item.isSelect = false;
      }
    });
  } else {
    if (index < list.value.length) {
      list.value[index].isSelect = !list.value[index].isSelect;
    }
  }
};

const subViewTouchStart = ref(false);
// 触摸开始
const converstationTouchStart = () => {
  subViewTouchStart.value = true;
};

// 触摸结束
const converstationTouchEnd = () => {
  timer.value = setTimeout(() => {
    subViewTouchStart.value = false;
  }, 100);
};

// 清空会话选择
const clearConversationSelect = () => {
  list.value.forEach((item: any) => {
    item.isSelect = false;
  });
};

//负责AI发送内容
const copyAiContent = (content: string) => {
  showAiDialog.value = false;
  if (chatBottomRef.value) {
    chatBottomRef.value?.addAiReplayContent(content);
  }
};

// 发送文本信息
const sendTextMsg = (text: string, isAi = false) => {
  const textObj = {
    id: generateUUID(),
    chatType: KKConversationType.text,
    source: KKConversationSource.artificial,
    time: "",
    from: KKConversationFrom.me,
    text: text,
    status: KKConversationStatus.loading,
    isSelect: false,
    isAiReplay: isAi,
  };
  list.value.push(textObj);
  aswerMessageSend(textObj);
};
// 发送图片和视频
const sendImageAndVideo = (tempFilePaths: []) => {
  tempFilePaths.forEach(async (item: any) => {
    if (item.fileType === "image") {
      const imgObj = {
        id: generateUUID(),
        source: KKConversationSource.artificial,
        chatType: KKConversationType.img,
        from: KKConversationFrom.me,
        tempFilePath: item.tempFilePath,
        text: "",
        status: KKConversationStatus.loading,
      };
      //图片
      list.value.push(imgObj);
      timer.value = setTimeout(() => {
        scrollToBottom();
      }, 30);
      const fileUrl = await uploadFile(
        item.tempFilePath,
        OSSFilePath.answerHivePic
      ).catch(() => {});
      if (fileUrl) {
        const index = findConversationIndex(imgObj.id);
        if (index < list.value.length) {
          list.value[index].text = fileUrl;
        }
        aswerMessageSend(imgObj);
      }
    } else if (item.fileType === "video") {
      const videoObj = {
        id: generateUUID(),
        source: KKConversationSource.artificial,
        chatType: KKConversationType.video,
        from: KKConversationFrom.me,
        tempFilePath: item.tempFilePath,
        tempPoster: item.thumbTempFilePath,
        text: "",
        videoPoster: "",
        status: KKConversationStatus.loading,
      };
      //视频
      list.value.push(videoObj);
      timer.value = setTimeout(() => {
        scrollToBottom();
      }, 30);
      const videoUrl = await uploadFile(
        item.tempFilePath,
        OSSFilePath.answerHiveVideo
      ).catch(() => {});
      const videoPosterUrl = await uploadFile(
        item.thumbTempFilePath,
        OSSFilePath.answerHivePic
      ).catch(() => {});
      if (videoUrl && videoPosterUrl) {
        const index = findConversationIndex(videoObj.id);
        if (index < list.value.length) {
          list.value[index].text = videoUrl;
          list.value[index].videoPoster = videoPosterUrl;
        }
        aswerMessageSend(videoObj);
      }
    }
  });
};

// 发送音频
const uploadAudio = async (filePath: string, duration: number) => {
  const aduioObj = {
    id: generateUUID(),
    source: KKConversationSource.artificial,
    chatType: KKConversationType.audio,
    from: KKConversationFrom.me,
    text: filePath,
    duration: duration,
    status: KKConversationStatus.loading,
  };
  //音频
  list.value.push(aduioObj);
  timer.value = setTimeout(() => {
    scrollToBottom();
  }, 30);
  const fileUrl = await uploadFile(filePath, OSSFilePath.answerHiveAudio).catch(
    () => {}
  );
  if (fileUrl) {
    const index = findConversationIndex(aduioObj.id);
    if (index < list.value.length) {
      list.value[index].text = fileUrl;
    }
    // #ifdef MP-WEIXIN
    wx.getFileSystemManager().unlink({
      filePath: filePath,
      success: () => {},
      fail: () => {},
    });
    // #endif
    aswerMessageSend(aduioObj);
  }
};

// 消息发送
// text 发送的内容 type 消息类型 index 会话索引
const aswerMessageSend = async (sendData: any) => {
  timer.value = setTimeout(() => {
    scrollToBottom();
  }, 30);
  const index = findConversationIndex(sendData.id);
  let answerWay = 1;
  if (sendData.isAiReplay) {
    answerWay = 3;
  }
  if (sendData.chatType === KKConversationType.exam) {
    answerWay = 2;
  }
  const param = {
    requestId: currentId.value,
    type: 2, // 1：提问,2：回答，3：追问, 4:自动回复消息 5：流转信息
    productId: productId.value,
    questionIds: sendData.questionIds || [],
    answerWay: answerWay, // 回复方式1：人工回复，2：试题推送回复，3：ai回复
    contentFlag: 1, //内容标识 1：人工，2：系统
    answerContent: getAnswerContent(sendData),
  };
  const isSendExam =
    sendData.chatType === KKConversationType.exam ? true : false;
  if (isSendExam) {
    showLoading.value = true;
  }
  const data = (await KKAswerApi.addResponseProt(param).catch(() => {})) as any;
  if (isSendExam) {
    showLoading.value = false;
  }
  if (data && Number(data.code) === 10000) {
    if (isSendExam) {
      list.value.push(sendData);
      timer.value = setTimeout(() => {
        scrollToBottom();
      }, 30);
    } else {
      if (index < list.value.length) {
        list.value[index].status = KKConversationStatus.success;
      }
    }
  } else {
    if (sendData.chatType === KKConversationType.audio) {
      if (index < list.value.length) {
        list.value.splice(index, 1);
      }
    } else {
      if (!isSendExam) {
        if (index < list.value.length) {
          list.value[index].status = KKConversationStatus.fail;
        }
      }
    }
  }
};

// 根据会话id查找会话index
const findConversationIndex = (id: string) => {
  return list.value.findIndex((item: any) => item.id === id);
};

// 选择AI回复功能
const bottomAiReplayTap = () => {
  isSelectMode.value = true;
  bottomViewType.value = "ai";
  footerHeight.value = aiFooterHeight;
};

// 获取AI和推送试题的参数messages内容
const getAiOrExamParamMessages = (list: []) => {
  let messages: any = [];
  list.forEach((item) => {
    let type = "text"; // 消息类型 text-文本 img-图片
    let role = "student"; //角色 student-学生  teacher-老师
    if (item.chatType === KKConversationType.text) {
      type = "text";
    } else if (item.chatType === KKConversationType.img) {
      type = "img";
    }
    if (item.from === KKConversationFrom.me) {
      role = "teacher";
    } else if (item.from === KKConversationFrom.other) {
      role = "student";
    }
    messages.push({
      type,
      content: item.text,
      role,
    });
  });
  return messages || [];
};

// AI回复选择会话
const aiReplySelectConversation = async (aiList: []) => {
  if (showLoading.value) {
    return;
  }
  if (!aiList) {
    const selectList = list.value.filter((item) => item.isSelect);
    if (selectList.length === 0) {
      kkToast.showToast("请选择会话");
      return;
    }
    aiList = [];
  }
  let aiReplayList = [];
  if (aiList.length > 0) {
    aiReplayList = aiList;
  } else {
    aiReplayList = list.value.filter((item: any) => item.isSelect);
  }
  if (aiReplayList && aiReplayList.length > 0) {
    let messages: any = getAiOrExamParamMessages(aiReplayList);
    aiReplayRequestParam.value = {
      requestId: currentId.value,
      productId: productId.value,
      messages: messages,
    };
    showLoading.value = false;
    showAiDialog.value = true;
    isSelectMode.value = false;
    bottomViewType.value = "normal";
    footerHeight.value = normalFooterHeight;
    clearConversationSelect();
  } else {
    kkToast.showToast("请选择会话");
  }
};

const similarExamDialogRef = ref();
// 选择视图推送功能
const bottomPushExamTap = async () => {
  if (showLoading.value) {
    return;
  }
  const filterList = [];
  let meAnswerFlag = false;
  for (var i = list.value.length - 1; i >= 0; i--) {
    const item = list.value[i];
    if (item.from === KKConversationFrom.me) {
      meAnswerFlag = true;
    }
    if (
      !meAnswerFlag &&
      item.from === KKConversationFrom.other &&
      item.answerWay === 1 &&
      (item.chatType === KKConversationType.text ||
        item.chatType === KKConversationType.img)
    ) {
      if (filterList.length < 5) {
        if (item.text) {
          filterList.push(item);
        }
      }
    }
  }
  if (filterList && filterList.length > 0) {
    let messages: any = getAiOrExamParamMessages(filterList);
    const param = {
      requestId: currentId.value,
      productId: productId.value,
      messages: messages,
    };
    showLoading.value = true;
    const data = (await KKAswerApi.getSimilarQuestionsProt(param).catch(() => {
      showLoading.value = false;
    })) as any;
    if (data && Number(data.code) === 10000) {
      showLoading.value = false;
      showExamDialog.value = true;
      similarExamDialogRef.value?.initSimilarList(data.data);
      clearConversationSelect();
    }
  } else {
    kkToast.showToast("暂无可推送的会话");
  }
};

// 确定推送试题
const confirmPushExam = (questionIds: []) => {
  showExamDialog.value = false;
  const examObj = {
    id: generateUUID(),
    chatType: KKConversationType.exam,
    from: KKConversationFrom.me,
    source: KKConversationSource.artificial,
    status: KKConversationStatus.success,
    questionIds: questionIds,
  };
  aswerMessageSend(examObj);
};
</script>

<style lang="scss" scoped>
.KKNavBar {
  position: fixed;
  top: 300px;
  height: 44px;
  width: 100vw;
  z-index: 999;
}
.conversationBg {
  margin-top: 40rpx;
  margin-left: 32rpx;
  margin-right: 32rpx;
}
</style>
